<template>
  <Container class="sale-list">
    <div slot="header" class="container-header large">
      <Form class="search">
        <Row>
          <i-col span="5">
            <FormItem label="促销类型">
              <Select v-model="list.form.activityType" clearable filterable @on-change="onSearchBtnClick">
                <Option v-for="item in options.typeList" :key="item.value" :value="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="促销名称">
              <Input v-model="list.form.activityName" placeholder="请输入促销名称" @on-enter="onSearchBtnClick" />
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem label="促销编码">
              <Input v-model="list.form.activitySn" placeholder="请输入促销编码" @on-enter="onSearchBtnClick" />
            </FormItem>
            <FormItem label="活动标签">
              <Select v-model="list.form.activityTag" clearable filterable @on-change="onSearchBtnClick">
                <Option v-for="(item, index) in factoryTag" :key="index" :value="item.id">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem label="商品搜索">
              <Input v-model="list.form.productSn" placeholder="请输入商品编码或商品名称" @on-enter="onSearchBtnClick" />
            </FormItem>
            <FormItem label="促销状态">
              <Select v-model="list.form.activityStatus" clearable @on-change="onSearchBtnClick">
                <Option v-for="item in options.statusList" :key="item.value" :value="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="7">
            <FormItem label="时间">
              <DatePicker
                v-model="list.form.date"
                format="yyyy-MM-dd"
                type="daterange"
                placement="bottom-start"
                placeholder="选择日期"
                @on-enter="onSearchBtnClick"
              />
            </FormItem>
            <FormItem label="SKU编码/商品编码" class="w160">
              <Input v-model="list.form.skuId" placeholder="请输入SKU编码/商品编码" @on-enter="onSearchBtnClick" />
            </FormItem>
          </i-col>
          <i-col class-name="search" span="2">
            <Button class="btn-search large" type="primary" icon="ios-search" @click="onSearchBtnClick" />
          </i-col>
        </Row>
      </Form>
    </div>
    <Tabs v-model="tab">
      <Button
        slot="extra"
        type="primary"
        size="large"
        icon="ios-trash"
        class="mr"
        @click="onBatchDelete"
      >批量删除</Button>
      <TabPane label="已创建的促销活动" name="tab1">
        <Table
          ref="selection"
          :height="options.tableHeight"
          stripe
          :columns="list.columns"
          :data="list.data"
          @on-select="onSelect"
          @on-select-all="onSelect"
          @on-selection-change="onSelect"
        />
        <div class="pager">
          <Page
            :total="list.totalItem"
            :current="list.currentPage"
            :page-size="list.pageSize"
            show-sizer
            placement="top"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
          />
        </div>
        <Loader :status="list.status" @refresh="onSearchBtnClick" />
      </TabPane>
    </Tabs>
  </Container>
</template>
<script>
import { formatDate, clearEmpty } from '@/util'
import table from '@/table'
import SaleListData from './list/SaleListData'
import { mapGetters } from 'vuex'
export default {
  name: 'sales/list',
  data () {
    return {
      tab: 'tab1',
      list: SaleListData,
      selection: [],
      options: {
        tableHeight: 300,
        typeList: [
          { value: 0, label: '单品' },
          { value: 1, label: '赠品' },
          { value: 2, label: '满减' },
          { value: 3, label: '满赠' },
          { value: 4, label: '满减送' },
          { value: 5, label: '多买优惠' },
          { value: 6, label: '满额返券' },
          { value: 7, label: '工厂特价' }
        ],
        statusList: [
          { value: 0, label: '未审核' },
          { value: 1, label: '已驳回' },
          { value: 2, label: '未开始' },
          { value: 3, label: '进行中' },
          { value: 4, label: '已暂停' },
          { value: 5, label: '已结束' },
          { value: 6, label: '即将结束' },
          { value: 7, label: '下架' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'factoryTag'
    ])
  },
  mounted () {
    this.list.currentPage = ~~this.$route.query.currentPage || 1
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.initTable()
    this.onSearchBtnClick(1)
    this.$bus.$on('onChangePause', ({ item }) => this.onChangePause(item))
    this.$bus.$on('onDelete', ({ item, index }) => this.onDelete(item, index))
    this.$bus.$on('onChangeshelfBtn', ({ item }) => this.onChangeshelfBtn(item))
    this.$store.dispatch('getfactoryTag')
  },
  destroyed () {
    this.$bus.$off()
  },
  methods: {
    ...table,
    onSearchBtnClick (param) {
      if (param !== 1) {
        this.list.currentPage = 1
      }
      this.getData()
    },
    getData () {
      let param = {
        activityName: this.list.form.activityName,
        activitySn: this.list.form.activitySn,
        activityStatus: this.list.form.activityStatus,
        activityType: this.list.form.activityType,
        promotionTagId: this.list.form.activityTag,
        skuSn: this.list.form.skuId,
        productSn: this.list.form.productSn,
        size: this.list.pageSize,
        current: this.list.currentPage,
        shelfStatusEnum: 'ON'
      }
      if (this.list.form.date[0] && this.list.form.date[1] && this.list.form.date.length) {
        param.startDatetime = formatDate(this.list.form.date[0]) + ' 00:00:00'
        param.endDatetime = formatDate(this.list.form.date[1]) + ' 23:59:59'
      }
      this.list.status = 'loading'
      param = clearEmpty(param)
      this.$ajaxGet('/activity/page', param).then(data => {
        data.records = data.records || []
        this.list.data = data.records.map(item => {
          let text = ''
          // 先判断审核状态，如果是未审核或者驳回，促销状态显示“未审核”"驳回"， 按钮不显示“暂停”按钮，其他都有
          // 如果是已审核，再去判断是否暂停，如果是，促销状态显示“已暂停” ，按钮暂停变成 “取消暂停”，其他都有
          // 如果是非暂停，则去判断时间，如果当前时间在开始时间之前，促销状态显示“未开始”
          // 如果当前时间在开始和结束时间中间，促销状态显示“进行中”, 按钮都有
          // 如果当前时间在结束时间后面，促销状态显示“已结束”，按钮没有暂停
          switch (item.checkStatusEnum) {
            case 'UNCHECKED':
              text = '未审核'
              break
            case 'REJECT':
              text = '已驳回'
              break
            case 'PASS':
              switch (item.isPause) {
                case true:
                  text = '已暂停'
                  break
                case false:
                  let now = new Date()
                  let isEarly = this.compareDate(now, item.startDate)
                  let isLater = this.compareDate(now, item.endDate)
                  if (isEarly) {
                    text = '未开始'
                  } else if (!isEarly && isLater) {
                    text = '进行中'
                  } else if (!isEarly) {
                    text = '已结束'
                  }
                  break
              }
              break
          }
          if (item.shelfStatusEnum == 'UNDER' && item.checkStatusEnum !== 'REJECT') text = '下架'
          let disabled = item.promotionTypeDescription === '满额返券'
          return {
            ...item,
            statusText: text,
            _disabled: disabled
          }
        })
        this.list.totalItem = Number(data.total)
        this.list.currentPage = Number(data.current)
        this.backTableTop()
        this.list.status = 'pass'
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    // 暂停活动
    onChangePause (item) {
      let text = item.isPause ? '取消暂停' : '暂停'
      this.$Modal.confirm({
        title: text,
        content: `确定要${text}此活动吗？`,
        onOk: () => {
          let param = {
            isPause: !item.isPause
          }
          this.$ajaxPost(`/activity/is_pause/${item.id}`, param).then(() => {
            this.$Notice.success({
              title: `已${text}`
            })
            this.getData()
          })
        }
      })
    },
    // 下架
    onChangeshelfBtn (item) {
      let text = '下架'
      let url = `/activity/batch/shelf_status/${item.id}`
      if (item.shelfStatusEnum === 'ON') { // 确定要下架
      } else { // 确认要上架
        text = '上架'
        switch (item.activityTypeEnum) {
        // 满减送
          case 'FULL_CUT_GIFT':
            url = `/activity/full_cut_gift/shelf/${item.id}`
            break
            // 满赠
          case 'FULL_GIFT':
            url = `/activity/full_gift/shelf_status/${item.id}`
            break
            // 单品
          case 'SINGLE':
            url = `/activity/single/shelf_status/${item.id}`
            break
            // 赠品
          case 'GIFT':
            url = `/activity/gift/shelf_status/${item.id}`
            break
            // 满减
          case 'FULL_CUT':
            url = `/activity/full_cut/shelf_status/${item.id}`
            break
            // 多买优惠
          case 'BUY_MORE':
            url = `/activity/buy_more/shelf/${item.id}`
            break
            // 满额返券
          case 'FULL_COUPON':
            url = `/activity/full_gift_coupon/shelf/${item.id}`
            break
          case 'FACTORY_ACTIVITY':
            url = `/activity/factory_info/shelf/${item.id}`
            break
        }
      }
      this.$Modal.confirm({
        title: text,
        content: `确定要${text}此活动吗？`,
        onOk: () => {
          this.$ajaxPost(url).then(() => {
            this.$Notice.success({
              title: `已${text}`
            })
            this.getData()
          })
        }
      })
    },
    // 删除
    onDelete (item, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定要删除此活动吗？',
        onOk: () => {
          this.$ajaxPost(`/activity/del/batch/${item.id}`).then(() => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.list.data.splice(index, 1)
          })
        }
      })
    },
    onBatchDelete () {
      if (!this.selection.length) {
        this.$Notice.warning({
          title: '请勾选活动'
        })
        return
      }
      let ids = this.selection.map(obj => obj.id)
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除所选的活动？',
        onOk: () => {
          this.$ajaxPost(`/activity/del/batch/${ids}`).then(() => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.getData()
          })
        }
      })
    },
    onSelect (selection) {
      this.selection = selection
    },
    compareDate (value1, value2) {
      let date1 = new Date(value1).getTime()
      let date2 = new Date(value2).getTime()
      return (date1 < date2)
    },
    onPageChange (number) {
      this.list.currentPage = number
      this.$router.push({
        name: 'sales/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    },
    onPageSizeChange (pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.$router.push({
        name: 'sales/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    }
  }
}
</script>

